import { PageContainer } from '@ant-design/pro-layout';
import React, { useState, useEffect, useRef } from 'react';
import { Button, Card, Col, Modal, Form, Input, Select, message } from 'antd';
import { connect, history } from 'umi';
import ProTable, { EditableProTable } from '@ant-design/pro-table';
import ProForm from '@ant-design/pro-form';
import { ArrowLeftOutlined } from '@ant-design/icons';

const defaultData = [
  {
    id: 624748504,
    url: '',
    enable: true,
  },
];

const VideoEdit = ({ dispatch, submitting, location }) => {
  const [form] = Form.useForm();
  const [singleInfo, setSingleInfo] = useState();
  const [editableKeys, setEditableRowKeys] = useState([]);

  const queryInfo = async () => {
    dispatch({
      type: 'functionAndVideo/single',
      payload: {
        functionTargetId: location.query.id,
      },
      callback: (res) => {
        if (res) {
          setSingleInfo(res);
          form.setFields([
            {
              name: 'videos',
              value: res.functionVideoVos?.length ? res.functionVideoVos : defaultData,
            },
          ]);
          let keys = defaultData.map((item) => item.id);
          if (res.functionVideoVos?.length) {
            keys = res.functionVideoVos?.map((item) => item.id);
          }
          setEditableRowKeys(keys);
        }
      },
    });
  };
  useEffect(() => {
    queryInfo();
  }, []);

  const columnsModal = [
    {
      title: '视频链接',
      dataIndex: 'url',
      width: '70%',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [
            { required: true, message: '请输入视频链接' },
            // () => ({
            //   validator(_, value) {
            //     const arr = Object.values(form.getFieldsValue());
            //     const otherData = arr.filter((item, index) => index !== rowIndex);
            //     let bool = otherData.some((item) => {
            //       return item.url === value;
            //     });
            //     return bool ? Promise.reject('请勿重复输入视频链接') : Promise.resolve();
            //   },
            // }),
          ],
        };
      },
    },
    {
      title: '状态',
      dataIndex: 'enable',
      key: 'enable',
      valueType: 'switch',
    },
    {
      title: '操作',
      valueType: 'option',
    },
  ];

  const onFinish = async (values) => {
    // 视频url去重提交
    let obj = {};
    let videos = values.videos?.reduce((cur, next) => {
      obj[next.url] ? '' : (obj[next.url] = true && cur.push(next));
      return cur;
    }, []); //设置cur默认类型为数组，并且初始值为空的数组

    dispatch({
      type: 'functionAndVideo/create',
      payload: {
        targetId: location.query.id,
        videos,
      },
      callback: (res) => {
        if (res) {
          message.success('操作成功');
          history.goBack();
        }
      },
    });
  };
  return (
    <PageContainer header={{ title: '' }}>
      <Card
        title={singleInfo?.title}
        extra={
          <Button onClick={() => history.goBack(1)} icon={<ArrowLeftOutlined />}>
            返回
          </Button>
        }
      >
        <ProForm
          form={form}
          onFinish={onFinish}
          onReset={queryInfo}
          submitter={{
            loading: submitting,
          }}
        >
          <ProForm.Item name="videos" trigger="onValuesChange">
            <EditableProTable
              rowKey="id"
              toolBarRender={false}
              columns={columnsModal}
              recordCreatorProps={{
                newRecordType: 'dataSource',
                position: 'end',
                record: () => ({
                  id: Date.now(),
                  enable: true,
                  url: '',
                }),
              }}
              editable={{
                type: 'multiple',
                editableKeys,
                onChange: setEditableRowKeys,
                actionRender: (row, _, dom) => {
                  return [dom.delete];
                },
              }}
            />
          </ProForm.Item>
        </ProForm>
      </Card>
    </PageContainer>
  );
};

export default connect(({ loading }) => ({
  submitting: loading.effects['functionAndVideo/create'],
}))(VideoEdit);
